package com.ddwl.shop.service;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.*;
import com.ddwl.common.exception.CommonException;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.FundsApi;
import com.ddwl.common.feign.api.GateApi;
import com.ddwl.common.feign.api.MessageApi;
import com.ddwl.common.feign.api.UserApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.funds.PaymentCreAndPayBo;
import com.ddwl.schema.bo.gate.DingTalkBo;
import com.ddwl.schema.bo.gate.wechat.WxTemplateMsgBo;
import com.ddwl.schema.bo.message.TempSentSmsBo;
import com.ddwl.schema.bo.shop.QueryShopApproveBo;
import com.ddwl.schema.bo.shop.ShopApproveBo;
import com.ddwl.schema.bo.shop.ShopBo;
import com.ddwl.schema.bo.shop.SubmitBo;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.funds.OrderPaymentVo;
import com.ddwl.schema.vo.gate.RegionVo;
import com.ddwl.schema.vo.order.OrderInfoVo;
import com.ddwl.schema.vo.order.OrderSpuVo;
import com.ddwl.schema.vo.shop.ShopApproveVo;
import com.ddwl.schema.vo.user.UserVo;
import com.ddwl.shop.dao.ShopApproveAssistRecordDao;
import com.ddwl.shop.dao.ShopApproveDao;
import com.ddwl.shop.dao.ShopApproveOrderDao;
import com.ddwl.shop.dao.ShopApproveRecordDao;
import com.ddwl.shop.dao.model.ShopApprove;
import com.ddwl.shop.dao.model.ShopApproveAssistRecord;
import com.ddwl.shop.dao.model.ShopApproveOrder;
import com.ddwl.shop.dao.model.ShopApproveRecord;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.util.StringUtil;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 门店审核
 *
 * @author wenbin
 * @version 1.0.0.RELEASE
 * @date 2020/3/5 11:00 上午
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ShopApproveService {

    private final ShopApproveDao shopApproveDao;
    private final ShopApproveRecordDao shopApproveRecordDao;
    private final RabbitTemplate rabbitTemplate;
    private final GateApi gateApi;
    private final UserApi userApi;
    private final ShopService shopService;
    private final ShopCategoryService shopCategoryService;
    private final MessageApi messageApi;
    private final ShopApproveAssistRecordDao shopApproveAssistRecordDao;
    private final ShopApproveOrderDao shopApproveOrderDao;
    private final FundsApi fundsApi;

    //帮扶基金
    @Value("${ddwl.assist_fund}")
    private BigDecimal assistFund;

    @Transactional(rollbackFor = Throwable.class)
    public void createShopApprove(ShopApproveBo bo) {
        ShopApprove approve = shopApproveDao.queryShopApprove(bo.getUserId(), ShopEnum.ApproveStatus.APPLY.getCode());
        ParamException.isNotNull(approve, "当前有未审批通过的申请");
        approve = shopApproveDao.queryByName(bo.getName());
        ParamException.isNotNull(approve, "当前店铺名称已有商家使用，请更换其他店铺名称");
        UserVo vo = userApi.getProfile(bo.getUserId()).getResult();
        bo.setUserTel(vo.getMobile());
        ShopApproveVo shopApproveVo = saveState1(bo);
        //ParamException.isFalse(vo.getMobile().equals(bo.getUserTel()),"手机号与用户不匹配");
        ShopApprove shopApprove = BeanConverUtils.convertBean(shopApproveVo, ShopApprove.class);
        shopApprove.setApproveStatus(ShopEnum.ApproveStatus.STATE1.getCode());
        shopApprove.setCreatedUserId(bo.getUserId());
        shopApprove.setHasAssistFund(0);
        shopApprove.setPayStatus(OrderEnum.PayStatus.CRE.getCode());
        shopApproveDao.insert(shopApprove);
        //重复校验 手机号
//        String userTelRepeat = shopApproveDao.checkUserTelRepeat();
//        ParamException.isTrue(StringUtil.isNotEmpty(userTelRepeat),"手机号"+userTelRepeat+"重复");
    }

    @Transactional(rollbackFor = Throwable.class)
    public void updateShopApprove(ShopApproveBo bo) {
        //只有已取消或者已拒绝的单子才能修改
        ShopApprove shopApprove = shopApproveDao.selectByPrimaryKey(bo.getId());
        ParamException.isNull(shopApprove, "申请不存在");
        ParamException.isTrue(shopApprove.getApproveStatus() != null && ShopEnum.ApproveStatus.APPLY.getCode().equals(shopApprove.getApproveStatus()),
                "当前状态处于待审批,请联系管理员修改");
        ParamException.isTrue(shopApprove.getApproveStatus() != null && ShopEnum.ApproveStatus.PASS.getCode().equals(shopApprove.getApproveStatus()),
                "当前状态审批通过,请联系管理员修改");
        if (StringUtils.hasText(bo.getName())) {
            ShopApprove approve = shopApproveDao.queryByName(bo.getName());
            if (approve != null && approve.getId() != bo.getId()) {
                throw new CommonException("当前店铺名称已有商家使用，请更换其他店铺名称");
            }
        }
        ShopApproveVo vo = new ShopApproveVo();
        if (bo.getApproveStatus().equals(ShopEnum.ApproveStatus.STATE1.getCode())) {
            vo = saveState1(bo);
        }
        if (bo.getApproveStatus().equals(ShopEnum.ApproveStatus.STATE2.getCode())) {
            vo = saveState2(bo, shopApprove.getApproveStatus());
        }
/*        if (bo.getApproveStatus().equals(ShopEnum.ApproveStatus.STATE3.getCode())){
            vo = saveState3(bo);
        }*/
        ShopApprove shopApprove1 = BeanConverUtils.convertBean(vo, ShopApprove.class);
        shopApprove1.setModifiedUserId(bo.getUserId());
        if (!CollectionUtils.isEmpty(vo.getStoreImg1())) {
            shopApprove1.setStoreImg1(String.join(",", bo.getStoreImg1()));
        }
        shopApproveDao.updateShopApprove(shopApprove1);
    }

    @Transactional(rollbackFor = Throwable.class)
    public void cancelShopApprove(String shopApproveId, String userId) {
        ShopApprove shopApprove = shopApproveDao.selectByPrimaryKey(shopApproveId);
        ParamException.isNull(shopApprove, "申请不存在");
        ParamException.isTrue(shopApprove.getApproveStatus() != null && !ShopEnum.ApproveStatus.APPLY.getCode().equals(shopApprove.getApproveStatus()),
                "只有待审批才能取消申请");
        shopApproveDao.cancelShopApprove(shopApproveId, userId);
    }

    @Transactional(rollbackFor = Throwable.class)
    public String submitShopApprove(String userId, SubmitBo submitBo) {
        ShopApprove shopApprove = getShopApprove(userId);
        ParamException.isNull(shopApprove, "申请不存在");
        ParamException.isTrue(shopApprove.getApproveStatus() != null && !(shopApprove.getApproveStatus().equals(ShopEnum.ApproveStatus.STATE2.getCode())
                        || shopApprove.getApproveStatus().equals(ShopEnum.ApproveStatus.REJECT.getCode())),
                "当前状态不能提交审批");
        String result = null;

        if (ShopEnum.PayStatus.PAY_SUCCESS.getCode().equals(shopApprove.getPayStatus()) && (shopApprove.getApproveStatus().equals(ShopEnum.ApproveStatus.REJECT.getCode())
                || shopApprove.getApproveStatus().equals(ShopEnum.ApproveStatus.STATE2.getCode()))) {
            shopApproveDao.submitShopApprove(shopApprove.getId());
        } else {
            result = createApproveOrder(shopApprove, submitBo);
        }
        ((ShopApproveService) AopContext.currentProxy()).sendWechatMsgForApplySubmit(shopApprove);
        return result;
    }

    @Async
    public void sendWechatMsgForApplySubmit(ShopApprove shopApprove) {
        String openId = userApi.getWechatOpenId(shopApprove.getUserId()).getResult();
        if (StrUtil.isNotEmpty(openId)) {
            String timeStr = DateUtil.formatDateTime(Instant.now());
            WxTemplateMsgBo template = new WxTemplateMsgBo();
            template.setTouser(openId);
            template.setTemplate_id(WechatTemplateEnum.APPLY_SUBMIT.getTemplateId());
            template.setTopcolor("#353535");
            WxTemplateMsgBo.TemplateData data = template.new TemplateData();
            data.setFirst(template.new Node("尊敬的" + shopApprove.getUserName() + "，您的开店申请已提交成功：", "#54529E"));
            data.setKeyword1(template.new Node("店铺入驻申请", "#54529E"));
            data.setKeyword2(template.new Node(timeStr, "#54529E"));
            data.setRemark(template.new Node("你的申请已经提交成功，我们会在3个工作日内反馈结果，请关注公众号消息以及短信提醒。", "#353535"));
            template.setData(data);
            gateApi.tempMessagePush(template);
        }
    }

    public PageVo<ShopApproveVo> page(PageBo<QueryShopApproveBo> boPageBo) {
        QueryShopApproveBo param = boPageBo.getParam();
        List<Integer> approveStatusList = new ArrayList<>();
        approveStatusList.add(ShopEnum.ApproveStatus.APPLY.getCode());
        approveStatusList.add(ShopEnum.ApproveStatus.PASS.getCode());
        approveStatusList.add(ShopEnum.ApproveStatus.REJECT.getCode());
        param.setApproveStatusList(approveStatusList);
        PageHelper.startPage(boPageBo.getPage(), boPageBo.getPageSize(), MySqlUtil.orderBy(boPageBo.getSort(), boPageBo.isAsc()));
        PageInfo<ShopApproveVo> info = new PageInfo(shopApproveDao.queryShopApproveList(param));
        List<ShopApproveVo> list = BeanConverUtils.convertBeanList(info.getList(), ShopApproveVo.class);
        list.stream().forEach(o -> {
            if (StringUtil.isNotEmpty(o.getCategory())) {
                o.setShopCategoryVoList(shopCategoryService.getShopCategory(o.getCategory()));
            }
        });
        return new PageVo<>(info.getTotal(), boPageBo.getPage(), boPageBo.getPageSize(), list);
    }

    public ShopApproveVo getById(String userId) {
        ShopApprove bo = new ShopApprove();
        bo.setUserId(userId);
        ShopApprove shopApprove = shopApproveDao.selectOne(bo);
        if (shopApprove == null) {
            return null;
        }
        ShopApproveVo shopApproveVo = BeanConverUtils.convertBean(shopApprove, ShopApproveVo.class);
        if (StringUtil.isNotEmpty(shopApprove.getStoreImg1())) {
            shopApproveVo.setStoreImg1(Arrays.asList(shopApprove.getStoreImg1().split(",")));
        }
        if (StringUtil.isNotEmpty(shopApproveVo.getCategory())) {
            shopApproveVo.setShopCategoryVoList(shopCategoryService.getShopCategory(shopApproveVo.getCategory()));
        }
        return shopApproveVo;
    }

    public ShopApproveVo getByIdConsole(String id) {
        ShopApprove shopApprove = shopApproveDao.selectByPrimaryKey(id);
        if (shopApprove == null) {
            return null;
        }
        ShopApproveVo shopApproveVo = BeanConverUtils.convertBean(shopApprove, ShopApproveVo.class);
        if (StringUtil.isNotEmpty(shopApprove.getStoreImg1())) {
            shopApproveVo.setStoreImg1(Arrays.asList(shopApprove.getStoreImg1().split(",")));
        }
        if (StringUtil.isNotEmpty(shopApproveVo.getCategory())) {
            shopApproveVo.setShopCategoryVoList(shopCategoryService.getShopCategory(shopApproveVo.getCategory()));
        }
        return shopApproveVo;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteShopApprove(String approveId, String userId) {
        ParamException.isNull(approveId, "申请id为空");
        shopApproveDao.deleteById(approveId, userId);
    }


    public void rejectShopApprove(String approveId, String rejectReason, String userId) {
        ParamException.isNull(approveId, "申请id为空");
        ShopApprove shopApprove = shopApproveDao.selectByPrimaryKey(approveId);
        ParamException.isNull(shopApprove, "申请不存在");
        ParamException.isFalse(shopApprove.getApproveStatus().equals(ShopEnum.ApproveStatus.APPLY.getCode()), "只有提交审批状态的可以拒绝");
        shopApprove.setId(approveId);
        shopApprove.setRejectReason(rejectReason);
        shopApprove.setModifiedUserId(userId);
        shopApprove.setApproveStatus(ShopEnum.ApproveStatus.REJECT.getCode());
        shopApproveDao.updateByPrimaryKeySelective(shopApprove);
        saveShopApproveRecord(approveId, rejectReason, userId, ShopEnum.ApproveStatus.REJECT.getCode());
    }

    @Transactional(rollbackFor = Exception.class)
    public void passShopApprove(String approveId, String userIdNew, Integer shopType) {
        ParamException.isNull(approveId, "申请id为空");
        ShopApprove shopApprove = shopApproveDao.selectByPrimaryKey(approveId);
        ParamException.isNull(shopApprove, "申请不存在");
        ParamException.isTrue(shopApprove.getApproveStatus().equals(ShopEnum.ApproveStatus.PASS.getCode()), "当前审批已通过,无需重复审批");
        ParamException.isTrue(shopApprove.getPayStatus() != null && !ShopEnum.PayStatus.PAY_SUCCESS.getCode().equals(shopApprove.getPayStatus()), "当前申请未付款,无法通过");
        pass(shopApprove, userIdNew, shopType);
    }

    @Transactional(rollbackFor = Exception.class)
    public void forcePassShopApprove(String approveId, String userIdNew, Integer shopType) {
        ParamException.isNull(approveId, "申请id为空");
        ShopApprove shopApprove = shopApproveDao.selectByPrimaryKey(approveId);
        ParamException.isNull(shopApprove, "申请不存在");
        pass(shopApprove, userIdNew, shopType);
    }

    private void pass(ShopApprove shopApprove, String userIdNew, Integer type) {
        shopApprove.setRejectReason("");
        shopApprove.setModifiedUserId(userIdNew);
        shopApprove.setApproveStatus(ShopEnum.ApproveStatus.PASS.getCode());
        shopApproveDao.updateByPrimaryKeySelective(shopApprove);
        saveShopApproveRecord(shopApprove.getId(), "", userIdNew, ShopEnum.ApproveStatus.PASS.getCode());
        //生成店铺信息
        ShopBo shopBo = BeanConverUtils.convertBean(shopApproveDao.selectByPrimaryKey(shopApprove.getId()), ShopBo.class, "id");
        shopBo.setType(type);
        shopService.createShop(shopBo, shopApprove.getUserId());
        ((ShopApproveService) AopContext.currentProxy()).asyncMessage(shopApprove);
    }

    @Async
    public void asyncMessage(ShopApprove shopApprove) {
        if (null != shopApprove) {
            String openId = userApi.getWechatOpenId(shopApprove.getUserId()).getResult();
            if (StrUtil.isNotEmpty(openId)) {
                String timeStr = DateUtil.formatDateTime(Instant.now());
                WxTemplateMsgBo template = new WxTemplateMsgBo();
                template.setTouser(openId);
                template.setTemplate_id(WechatTemplateEnum.APPLY_RESULT.getTemplateId());
                template.setTopcolor("#353535");
                WxTemplateMsgBo.TemplateData data = template.new TemplateData();
                if (ShopEnum.ApproveStatus.PASS.getCode().equals(shopApprove.getApproveStatus())) {
                    data.setFirst(template.new Node("尊敬的" + shopApprove.getUserName() + "，您的开店申请已审核通过：", "#54529E"));
                    data.setKeyword1(template.new Node("店铺入驻申请", "#54529E"));
                    data.setKeyword2(template.new Node("通过", "#54529E"));
                    data.setKeyword3(template.new Node(timeStr, "#54529E"));
                    data.setRemark(template.new Node("感谢您入驻五八马，我们一定竭诚为您服务！", "#353535"));
                } else if (ShopEnum.ApproveStatus.REJECT.getCode().equals(shopApprove.getApproveStatus())) {
                    data.setFirst(template.new Node("尊敬的" + shopApprove.getUserName() + "，您的开店申请被拒绝：", "#54529E"));
                    data.setKeyword1(template.new Node("店铺入驻申请", "#54529E"));
                    data.setKeyword2(template.new Node("拒绝", "#54529E"));
                    data.setKeyword3(template.new Node(timeStr, "#54529E"));
                    data.setRemark(template.new Node("拒绝原因[" + shopApprove.getRejectReason() + "]，请修改后重新提交审核！", "#353535"));
                }
                template.setData(data);
                gateApi.tempMessagePush(template);
            }
            sentSms(shopApprove.getUserTel());
        }
    }

    private void sentSms(String telPhone) {
        TempSentSmsBo tempSentSmsBo = new TempSentSmsBo();
        tempSentSmsBo.setToPhone(telPhone);
        tempSentSmsBo.setTemplateCode(SmsTempCodeEnum.SHOP_APPROVE_PASS.getCode());
        messageApi.sentSms(tempSentSmsBo);
    }

    /**
     * 记录审批记录
     */
    private void saveShopApproveRecord(String approveId, String rejectReason, String userIdNew, Integer approveCode) {
        ShopApproveRecord shopApproveRecord = new ShopApproveRecord();
        shopApproveRecord.setRejectReason(rejectReason);
        shopApproveRecord.setApproveStatus(approveCode);
        shopApproveRecord.setUserId(userIdNew);
        shopApproveRecord.setShopApproveId(approveId);
        shopApproveRecordDao.insert(shopApproveRecord);
    }

    /**
     * 未审批状态1
     */
    private ShopApproveVo saveState1(ShopApproveBo bo) {
        ParamException.isBlank(bo.getUserName(), "申请人姓名为空");
        ParamException.isBlank(bo.getUserId(), "申请人id为空");
        ParamException.isBlank(bo.getUserTel(), "申请人手机号为空");
        ParamException.isBlank(bo.getUserIdCard(), "身份证号为空");
        ParamException.isBlank(bo.getIdCardFront(), "身份证正面为空");
        ParamException.isBlank(bo.getIdCardBack(), "身份证背面为空");
        ParamException.isFalse(IdcardUtil.isValidCard(bo.getUserIdCard()), "请输入正确身份证号");
        ShopApproveVo shopApproveVo = new ShopApproveVo();

        if (StringUtil.isNotEmpty(bo.getId())) {
            shopApproveVo.setId(bo.getId());
            shopApproveVo.setApproveStatus(null);
        } else {
            shopApproveVo.setApproveStatus(ShopEnum.ApproveStatus.STATE1.getCode());
        }
        shopApproveVo.setUserId(bo.getUserId());

        shopApproveVo.setUserName(bo.getUserName());
        shopApproveVo.setUserTel(bo.getUserTel());
        shopApproveVo.setUserIdCard(bo.getUserIdCard());
        shopApproveVo.setIdCardFront(bo.getIdCardFront());
        shopApproveVo.setIdCardBack(bo.getIdCardBack());
        return shopApproveVo;
    }

    /**
     * 未审批状态2
     */
    private ShopApproveVo saveState2(ShopApproveBo bo, Integer approveStatus) {
        ParamException.isBlank(bo.getId(), "id为空");
        ParamException.isBlank(bo.getName(), "商家名字为空");
        ParamException.isNull(bo.getType(), "门店类型为空");
        ParamException.isBlank(bo.getCertificateCode(), "店铺证件号为空");
        ParamException.isBlank(bo.getRegionId(), "区域id为空");
        ParamException.isBlank(bo.getAddress(), "详细地址为空");
        ParamException.isBlank(bo.getPostcode(), "邮编为空");
        ParamException.isBlank(bo.getCertificateImg(), "营业执照为空");
        ParamException.isNull(bo.getCertificateType(), "营业执照类型为空");
        ParamException.isNull(bo.getShopCategoryVoList(), "店铺类别为空");
        ParamException.isNull(bo.getLng(), "经度为空");
        ParamException.isNull(bo.getLat(), "纬度为空");
        ParamException.isBlank(bo.getCoverImg(), "商家封面为空");
        ParamException.isNull(bo.getStoreImg1(), "店内展示图1为空");


        ShopApproveVo shopApproveVo = new ShopApproveVo();
/*        if (!(approveStatus.equals(ShopEnum.ApproveStatus.STATE1.getCode()) || approveStatus.equals(ShopEnum.ApproveStatus.STATE2.getCode()))){
            shopApproveVo.setApproveStatus(null);
        }else {
        }*/
        shopApproveVo.setApproveStatus(ShopEnum.ApproveStatus.STATE2.getCode());

        //设置分类
        if (!CollectionUtils.isEmpty(bo.getShopCategoryVoList())) {
            StringBuffer cate = new StringBuffer("");
            bo.getShopCategoryVoList().stream().forEach(o -> {
                cate.append(o.getShopCategoryCode()).append(",");
            });
            shopApproveVo.setCategory(cate.toString().substring(0, cate.length() - 1));
        }

/*        String regex = "^([159Y]{1})([1239]{1})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-90-9ABCDEFGHJKLMNPQRTUWXY])$";
        ParamException.isTrue(!bo.getCertificateCode().matches(regex),"营业执照不正确");*/

        shopApproveVo.setId(bo.getId());
        shopApproveVo.setName(bo.getName());
        shopApproveVo.setType(bo.getType());
        shopApproveVo.setCertificateCode(bo.getCertificateCode());
        shopApproveVo.setRegionId(bo.getRegionId());
        RegionVo regionVo = gateApi.geoRegion(bo.getRegionId()).getResult();
        shopApproveVo.setProvinceName(regionVo.getProvinceName());
        shopApproveVo.setCityName(regionVo.getCityName());
        shopApproveVo.setDistrictName(regionVo.getDistrictName());
        shopApproveVo.setAddress(bo.getAddress());
        shopApproveVo.setPostcode(bo.getPostcode());
        shopApproveVo.setCertificateImg(bo.getCertificateImg());
        shopApproveVo.setCertificateType(bo.getCertificateType());
        shopApproveVo.setCoverImg(bo.getCoverImg());
        shopApproveVo.setStoreImg1(bo.getStoreImg1());
        shopApproveVo.setLng(bo.getLng());
        shopApproveVo.setLat(bo.getLat());
        return shopApproveVo;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveShopAssistFund(String userId) {
        ShopApproveAssistRecord assistFund2 = getShopAssistFund(userId);
        ParamException.isNotNull(assistFund2, "当前用户有未使用的帮扶基金");
        ShopApproveAssistRecord shopApproveAssistRecord = new ShopApproveAssistRecord();
        shopApproveAssistRecord.setApproveUserId(userId);
        shopApproveAssistRecord.setUsed(0);
        shopApproveAssistRecord.setAmount(assistFund);
        shopApproveAssistRecordDao.insert(shopApproveAssistRecord);
        updateShopAssistStatus(userId);
    }

    /**
     * 更新帮扶基金领取状态
     */
    private void updateShopAssistStatus(String userIdNew) {
        ShopApprove shopApprove = getShopApprove(userIdNew);
        ParamException.isNull(shopApprove, "当前用户没有提交申请");
        ParamException.isTrue(shopApprove.getApproveStatus() != null
                && (ShopEnum.ApproveStatus.APPLY.getCode().equals(shopApprove.getApproveStatus()) || ShopEnum.ApproveStatus.PASS.getCode().equals(shopApprove.getApproveStatus())
                || ShopEnum.ApproveStatus.REJECT.getCode().equals(shopApprove.getApproveStatus()) || ShopEnum.ApproveStatus.CANCEL.getCode().equals(shopApprove.getApproveStatus())), "当前状态已不能领取帮扶基金");
        ShopApprove approve = new ShopApprove();
        approve.setHasAssistFund(1);
        approve.setId(shopApprove.getId());
        shopApproveDao.updateByPrimaryKeySelective(approve);
    }

    /**
     * 查询当前用户是否领过帮扶基金
     */
    private ShopApproveAssistRecord getShopAssistFund(String userIdNew) {
        ShopApproveAssistRecord shopApproveAssistRecord = new ShopApproveAssistRecord();
        shopApproveAssistRecord.setUsed(0);
        shopApproveAssistRecord.setApproveUserId(userIdNew);
        return shopApproveAssistRecordDao.selectOne(shopApproveAssistRecord);
    }

    /**
     * 查询当前用户的审批
     */
    private ShopApprove getShopApprove(String userIdNew) {
        ShopApprove shopApprove = new ShopApprove();
        shopApprove.setUserId(userIdNew);
        return shopApproveDao.selectOne(shopApprove);
    }


    /**
     * 下申请单
     *
     * @param shopApprove
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String createApproveOrder(ShopApprove shopApprove, SubmitBo submitBo) {
        ShopApproveOrder entity = new ShopApproveOrder();
        //校验是否有待付款的订单
        ShopApproveOrder selectOne = shopApproveOrderDao.queryShopApproveOrder(shopApprove.getId());

        if (selectOne != null && (ShopEnum.PayStatus.PEND_PAY.getCode().equals(selectOne.getStatus()) || ShopEnum.PayStatus.PAY_FAIL.getCode().equals(selectOne.getStatus()))) {
            if (ShopEnum.AssistFundStatus.UN_RECEIVE.getCode().equals(shopApprove.getHasAssistFund())) {
                return createPayOrder(selectOne, submitBo);
            }
            if (ShopEnum.AssistFundStatus.RECEIVED.getCode().equals(shopApprove.getHasAssistFund())) {
                if (selectOne.getAmount().compareTo(BigDecimal.valueOf(99)) == 0) {
                    return createPayOrder(selectOne, submitBo);
                }
                entity.setShopApproveId(shopApprove.getId());
                entity.setAmount(BigDecimal.valueOf(99));
                entity.setApproveUserId(shopApprove.getUserId());
                entity.setApproveUserName(shopApprove.getUserName());
                entity.setApproveUserTel(shopApprove.getUserTel());
                entity.setAssistAmount(assistFund);
                entity.setStatus(BaseEnum.ApplyEnum.CRE.getCode());
                shopApproveOrderDao.insert(entity);
                return createPayOrder(entity, submitBo);
/*                //领取帮扶金后提交
                entity.setId(selectOne.getId());
                entity.setStatus("20");
                entity.setAssistAmount(assistFund);
                entity.setPaymentType(2);
                shopApproveOrderDao.updateByPrimaryKeySelective(entity);
                //更新申请付款状态
                ShopApprove shop=new ShopApprove();
                shop.setId(shopApprove.getId());
                shop.setPayStatus("20");
                shop.setPaymentType(2);
                shop.setApproveStatus(ShopEnum.ApproveStatus.APPLY.getCode());
                shopApproveDao.updateByPrimaryKeySelective(shop);
                return null;*/
            }
        }

        entity.setShopApproveId(shopApprove.getId());
        entity.setAmount(assistFund);
        if (shopApprove.getHasAssistFund() != null && ShopEnum.AssistFundStatus.RECEIVED.getCode().equals(shopApprove.getHasAssistFund())) {
            entity.setAmount(BigDecimal.valueOf(99));
        }
        entity.setApproveUserId(shopApprove.getUserId());
        entity.setApproveUserName(shopApprove.getUserName());
        entity.setApproveUserTel(shopApprove.getUserTel());
        entity.setAssistAmount(BigDecimal.ZERO);
        entity.setStatus(BaseEnum.ApplyEnum.CRE.getCode());
        //有帮扶基金使用帮扶基金
/*        if (shopApprove.getHasAssistFund()==1){
            entity.setStatus("20");
            entity.setAssistAmount(assistFund);
            entity.setPaymentType(2);
            ShopApproveOrder insert = shopApproveOrderDao.insert(entity);
            //更新申请付款状态
            ShopApprove shop=new ShopApprove();
            shop.setId(shopApprove.getId());
            shop.setPayStatus("20");
            shop.setPaymentType(2);
            shop.setApproveStatus(ShopEnum.ApproveStatus.APPLY.getCode());
            shopApproveDao.updateByPrimaryKeySelective(shop);
            return null;
        }else {
         //没有帮扶基金生成付款单
            ShopApproveOrder insert = shopApproveOrderDao.insert(entity);
            return createPayOrder(insert,submitBo);
        }*/
        shopApproveOrderDao.insert(entity);
        return createPayOrder(entity, submitBo);
    }


    private String createPayOrder(ShopApproveOrder insert, SubmitBo submitBo) {
        PaymentCreAndPayBo payOrderCreBo = BeanConverUtils.convertBean(submitBo, PaymentCreAndPayBo.class);
        payOrderCreBo.setOrderId(insert.getId());
        payOrderCreBo.setUserId(insert.getApproveUserId());
        payOrderCreBo.setUserName(insert.getApproveUserName());
        payOrderCreBo.setOrderType(Integer.valueOf(OrderTypeEnum.assistFund.getCode()));
        payOrderCreBo.setTotalAmount(insert.getAmount());
        payOrderCreBo.setExpirationTime(DateUtil.getTimesMorning(5));
        payOrderCreBo.setPaymentType(submitBo.getPayType());
        payOrderCreBo.setPayOpenId(submitBo.getOpenId());
        payOrderCreBo.setNotifyMethod(RabbitMqConstants.ASSIST_FUND_NOTIFY_QUEUE);
        payOrderCreBo.setPayAppId(submitBo.getAppId());
        payOrderCreBo.setPayUserId(insert.getApproveUserId());
        payOrderCreBo.setPayUserName(insert.getApproveUserName());
        payOrderCreBo.setPayProduct(submitBo.getProduct());
        payOrderCreBo.setProduct(submitBo.getProduct());
        log.info("fundsApi.create param {}", JSON.toJSONString(payOrderCreBo));
        String payId = fundsApi.crePayment(payOrderCreBo).getResult();
        log.info("fundsApi.create result {}", JSON.toJSONString(payId));
        if (StringUtil.isNotEmpty(payId)) {
            return payId;
        }
        return null;
    }

    /**
     * 支付成功后回调用
     *
     * @param orderPayVo
     */
    public void orderPayCallBack(OrderPaymentVo orderPayVo) {
        log.info("method orderPayCallBack param {}", JSON.toJSONString(orderPayVo));
        ShopApproveOrder shopApproveOrder = shopApproveOrderDao.selectByPrimaryKey(orderPayVo.getOrderId());
        ParamException.isNull(shopApproveOrder, "门店申请不存在");
        //更新订单状态
        ShopApproveOrder approveOrder = new ShopApproveOrder();
        approveOrder.setId(shopApproveOrder.getId());
        approveOrder.setStatus(orderPayVo.getTradeStatus());
        approveOrder.setPaymentType(orderPayVo.getPayType());
        shopApproveOrderDao.updateByPrimaryKeySelective(approveOrder);
        //更新申请付款状态
        ShopApprove shop = new ShopApprove();
        shop.setId(shopApproveOrder.getShopApproveId());
        shop.setPayStatus(orderPayVo.getTradeStatus());
        shop.setPaymentType(orderPayVo.getPayType());
        //只处理成功请求
        if (orderPayVo.getTradeStatus() != null && orderPayVo.getTradeStatus().equals(OrderEnum.PayStatus.SUCCEED.getCode())) {
            ShopApprove exist = shopApproveDao.selectByPrimaryKey(shop.getId());
            shop.setApproveStatus(ShopEnum.ApproveStatus.APPLY.getCode());
            createDistOrder(orderPayVo, exist.getRegionId(), exist.getName());
            ((ShopApproveService) AopContext.currentProxy()).sendWechatMsgForPay(orderPayVo, exist.getName(), shopApproveOrder.getGmtCreated());
        }
        shopApproveDao.updateByPrimaryKeySelective(shop);
        //发送钉钉消息
        DingTalkBo bo1 = new DingTalkBo();
        bo1.setMessage("");
        bo1.setChannel(StatisticsEnum.channel.SHOP_APPROVE.getId());
        rabbitTemplate.convertAndSend(RabbitMqConstants.DINGDING_TALK_MESSAGE, JSON.toJSONString(bo1));
    }

    @Async
    public void sendWechatMsgForPay(OrderPaymentVo orderPayVo, String shopName, Instant time) {
        if (null != orderPayVo) {
            String openId = userApi.getWechatOpenId(orderPayVo.getUserId()).getResult();
            if (StrUtil.isNotEmpty(openId)) {
                if (null == time) {
                    time = Instant.now();
                }
                String timeStr = DateUtil.formatDateTime(time);
                WxTemplateMsgBo template = new WxTemplateMsgBo();
                template.setTouser(openId);
                template.setTemplate_id(WechatTemplateEnum.PAY_SUCCESS.getTemplateId());
                template.setTopcolor("#353535");
                WxTemplateMsgBo.TemplateData data = template.new TemplateData();
                data.setFirst(template.new Node("尊敬的" + orderPayVo.getUserName() + "，您的订单已支付成功：", "#54529E"));
                data.setKeyword1(template.new Node(orderPayVo.getOrderId(), "#54529E"));
                data.setKeyword2(template.new Node(orderPayVo.getAmount() + "元", "#54529E"));
                data.setKeyword3(template.new Node(shopName, "#54529E"));
                data.setKeyword4(template.new Node(timeStr, "#54529E"));
                data.setRemark(template.new Node("店铺入驻保证金已成功支付！", "#353535"));
                template.setData(data);
                gateApi.tempMessagePush(template);
            }
        }
    }

    /**
     * 创建分销单
     */
    private void createDistOrder(OrderPaymentVo orderPayVo, String regionId, String itemName) {
        //拼装佣金所需订单
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setAmount(orderPayVo.getAmount());
        orderInfoVo.setId(orderPayVo.getOrderId());
        orderInfoVo.setUserId(orderPayVo.getUserId());
        orderInfoVo.setPayAmount(orderPayVo.getAmount());
        UserVo vo = userApi.getProfile(orderPayVo.getUserId()).getResult();
        if (StringUtil.isEmpty(vo.getImmediateSuperior())) {
            orderInfoVo.setSource(orderPayVo.getUserId());
        } else {
            orderInfoVo.setSource(vo.getImmediateSuperior());
        }
        orderInfoVo.setPayTime(orderPayVo.getGmtCreated());
        orderInfoVo.setConfirmTime(orderPayVo.getGmtCreated());
        orderInfoVo.setRegionId(regionId);
        orderInfoVo.setShopId(orderPayVo.getShopId());
        List<OrderSpuVo> orderSpus = new ArrayList<>();
        orderInfoVo.setDistType(DistConstant.DistrConfigType.SHOP.getCode());
        OrderSpuVo orderSpuVo = new OrderSpuVo();
        orderSpuVo.setId(DistConstant.ShopApproveOrder.ORDER_ID.getCode());
        orderSpuVo.setRealPrice(BigDecimal.valueOf(100));
        orderSpuVo.setPrice(BigDecimal.valueOf(100));
        orderSpuVo.setProfitPrice(BigDecimal.valueOf(50));
        orderSpuVo.setItemName(itemName);
        orderSpuVo.setSkuDesc(DistConstant.ShopApproveOrder.SKU_DESC.getCode());
        orderSpuVo.setItemId(DistConstant.ShopApproveOrder.ITEM_ID.getCode());
        orderSpuVo.setSkuId(DistConstant.ShopApproveOrder.SKU_ID.getCode());
        orderSpuVo.setSkuQty(1);
        orderSpus.add(orderSpuVo);
        orderInfoVo.setSkuSnapshoot(JSON.toJSONString(orderSpus));

        String disOrder = JSON.toJSONString(orderInfoVo);
        rabbitTemplate.convertAndSend(RabbitMqConstants.DIST_SHOP_ORDER_CALCULATE_QUEUE, disOrder);
    }
}
